<template>
  <div class="user-profile">
    <el-page-header @back="goBack" v-if="!isCurrentUser">
      <template #content>
        <span class="text-large font-600 mr-3">用户主页</span>
      </template>
    </el-page-header>

    <div v-loading="loading" class="profile-content">
      <!-- 用户信息卡片 -->
      <el-card v-if="user" shadow="hover" class="user-info-card">
        <div class="user-header">
          <el-avatar :size="100" :src="avatarUrl">
            {{ user.username?.charAt(0).toUpperCase() }}
          </el-avatar>
          <div class="user-details">
            <h2>{{ user.username }}</h2>
            <p v-if="user.email" class="user-email">{{ user.email }}</p>
            <p v-if="user.phone" class="user-phone">{{ user.phone }}</p>
            <div class="user-stats" v-if="stats">
              <div class="stat-item">
                <span class="stat-value">{{ stats.posts_count || 0 }}</span>
                <span class="stat-label">动态</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ stats.total_favorites_count || 0 }}</span>
                <span class="stat-label">收藏</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ stats.itineraries_count || 0 }}</span>
                <span class="stat-label">行程</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ user.followers_count || 0 }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-value">{{ user.following_count || 0 }}</span>
                <span class="stat-label">关注</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="profile-tabs">
        <!-- 动态标签页 -->
        <el-tab-pane label="动态" name="posts">
          <div v-loading="postsLoading">
            <div v-if="posts.length > 0" class="posts-list">
              <el-card
                v-for="post in posts"
                :key="post.id"
                shadow="hover"
                class="post-card"
              >
                <div class="post-header">
                  <el-avatar :src="post.user_avatar" :size="40">
                    {{ post.user_username?.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <div class="post-user-info">
                    <h4>{{ post.user_username }}</h4>
                    <span class="post-time">{{ formatTime(post.created_at) }}</span>
                  </div>
                </div>
                <div class="post-content">
                  <p>{{ post.content }}</p>
                  <div v-if="post.images && post.images.length > 0" class="post-images">
                    <el-image
                      v-for="(img, index) in post.images"
                      :key="index"
                      :src="getImageUrl(img.image || img)"
                      :preview-src-list="post.images.map(i => getImageUrl(i.image || i))"
                      :initial-index="index"
                      fit="cover"
                      class="post-image"
                      lazy
                    />
                  </div>
                </div>
                <div class="post-footer">
                  <el-button
                    :type="post.is_liked ? 'danger' : 'default'"
                    size="small"
                    @click="toggleLike(post)"
                  >
                    <el-icon><StarFilled /></el-icon>
                    {{ post.likes_count || 0 }}
                  </el-button>
                  <el-button size="small" @click="showComments(post)">
                    <el-icon><ChatLineRound /></el-icon>
                    {{ post.comments_count || 0 }}
                  </el-button>
                </div>
              </el-card>
            </div>
            <el-empty v-else description="暂无动态" />
          </div>
        </el-tab-pane>

        <!-- 收藏标签页 -->
        <el-tab-pane label="收藏" name="favorites">
          <div v-loading="favoritesLoading">
            <el-tabs v-model="favoritesTab" type="card">
              <!-- 景点收藏 -->
              <el-tab-pane label="景点" name="attractions">
                <div v-if="favorites.attractions && favorites.attractions.length > 0" class="favorites-list">
                  <el-row :gutter="20">
                    <el-col
                      :xs="24"
                      :sm="12"
                      :md="8"
                      v-for="fav in favorites.attractions"
                      :key="fav.id"
                    >
                      <el-card shadow="hover" class="favorite-card" @click="viewAttraction(fav.attraction.id)">
                        <el-image
                          :src="fav.attraction.primary_image"
                          fit="cover"
                          class="favorite-image"
                        />
                        <h4>{{ fav.attraction.name }}</h4>
                        <p class="favorite-price">¥{{ fav.attraction.ticket_price }}</p>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
                <el-empty v-else description="暂无景点收藏" />
              </el-tab-pane>

              <!-- 路线收藏 -->
              <el-tab-pane label="路线" name="routes">
                <div v-if="favorites.routes && favorites.routes.length > 0" class="favorites-list">
                  <el-card
                    v-for="fav in favorites.routes"
                    :key="fav.id"
                    shadow="hover"
                    class="route-favorite-card"
                    @click="viewRoute(fav.route_plan.id)"
                  >
                    <h4>{{ fav.route_plan.start_attraction?.name || '路线规划' }}</h4>
                    <el-descriptions :column="2" size="small">
                      <el-descriptions-item label="预算">¥{{ fav.route_plan.budget }}</el-descriptions-item>
                      <el-descriptions-item label="总费用">¥{{ fav.route_plan.total_cost }}</el-descriptions-item>
                      <el-descriptions-item label="总距离">{{ fav.route_plan.total_distance }} 公里</el-descriptions-item>
                      <el-descriptions-item label="收藏时间">{{ formatTime(fav.created_at) }}</el-descriptions-item>
                    </el-descriptions>
                  </el-card>
                </div>
                <el-empty v-else description="暂无路线收藏" />
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { StarFilled, ChatLineRound } from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import { getApiBaseUrl, getImageUrl as getImageUrlUtil } from '../utils/apiConfig'

export default {
  name: 'UserProfile',
  components: {
    StarFilled,
    ChatLineRound
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const loading = ref(false)
    const postsLoading = ref(false)
    const favoritesLoading = ref(false)
    const user = ref(null)
    const stats = ref(null)
    const posts = ref([])
    const favorites = reactive({
      attractions: [],
      routes: []
    })
    const activeTab = ref('posts')
    const favoritesTab = ref('attractions')
    const userId = computed(() => parseInt(route.params.id))
    const currentUser = computed(() => store.state.user)
    const isCurrentUser = computed(() => {
      return currentUser.value && currentUser.value.id === userId.value
    })

    const avatarUrl = computed(() => {
      if (user.value?.avatar) {
        return user.value.avatar.startsWith('http')
          ? user.value.avatar
          : `${getApiBaseUrl()}${user.value.avatar}`
      }
      return null
    })

    const fetchUserProfile = async () => {
      loading.value = true
      try {
        const response = await TravelAPI.getUserProfile(userId.value)
        user.value = response
        stats.value = response.stats || {}
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '获取用户信息失败' })
        })
        ElMessage.error('获取用户信息失败')
      } finally {
        loading.value = false
      }
    }

    const fetchUserPosts = async () => {
      postsLoading.value = true
      try {
        const response = await TravelAPI.getUserPosts(userId.value)
        posts.value = (response.results || response || []).map(post => ({
          ...post,
          showComments: false
        }))
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '获取动态列表失败' })
        })
        posts.value = []
      } finally {
        postsLoading.value = false
      }
    }

    const fetchUserFavorites = async () => {
      favoritesLoading.value = true
      try {
        const response = await TravelAPI.getUserFavorites(userId.value)
        favorites.attractions = response.attractions || []
        favorites.routes = response.routes || []
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '获取收藏列表失败' })
        })
        favorites.attractions = []
        favorites.routes = []
      } finally {
        favoritesLoading.value = false
      }
    }

    const toggleLike = async (post) => {
      if (!currentUser.value) {
        ElMessage.warning('请先登录')
        return
      }
      try {
        const baseUrl = getApiBaseUrl()
        const token = store.state.token || localStorage.getItem('token')
        
        if (post.is_liked) {
          // 取消点赞
          await fetch(`${baseUrl}/api/social/posts/${post.id}/like/`, {
            method: 'DELETE',
            headers: {
              'Authorization': token ? `Token ${token}` : '',
              'Content-Type': 'application/json'
            }
          })
          post.is_liked = false
          post.likes_count = Math.max((post.likes_count || 1) - 1, 0)
        } else {
          // 点赞
          await fetch(`${baseUrl}/api/social/posts/${post.id}/like/`, {
            method: 'POST',
            headers: {
              'Authorization': token ? `Token ${token}` : '',
              'Content-Type': 'application/json'
            }
          })
          post.is_liked = true
          post.likes_count = (post.likes_count || 0) + 1
        }
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '操作失败' })
        })
        ElMessage.error('操作失败')
      }
    }

    /**
     * 显示/隐藏评论，并在首次展开时分页拉取评论
     * @param {Object} post - 动态对象
     */
    const showComments = async (post) => {
      post.showComments = !post.showComments
      if (post.showComments && !post.comments) {
        try {
          const resp = await TravelAPI.getPostComments(post.id, { page_size: 50 })
          post.comments = resp?.results || resp || []
        } catch (error) {
          import('../utils/errorHandler').then(({ handleApiError }) => {
            handleApiError(error, { defaultMessage: '获取评论失败' })
          })
          ElMessage.error('获取评论失败')
        }
      }
    }

    const viewAttraction = (attractionId) => {
      router.push(`/attractions/${attractionId}`)
    }

    /**
     * 查看路线详情（从分页历史中查询）
     * @param {number} routeId - 路线ID
     */
    const viewRoute = async (routeId) => {
      try {
        const historyData = await TravelAPI.getRouteHistory({ page_size: 50 })
        const routes = historyData.results || historyData || []
        const route = routes.find(r => r.id === routeId)
        if (route && route.share_code) {
          router.push(`/route-share/${route.share_code}`)
        } else {
          ElMessage.info('该路线未分享，无法查看详情')
        }
      } catch (error) {
        import('../utils/errorHandler').then(({ handleApiError }) => {
          handleApiError(error, { defaultMessage: '获取路线信息失败' })
        })
        ElMessage.error('获取路线信息失败')
      }
    }

    const goBack = () => {
      router.back()
    }

    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getImageUrl = (imagePath) => {
      if (!imagePath) return ''
      if (imagePath.startsWith('http')) return imagePath
      return getImageUrlUtil(imagePath)
    }

    // 监听标签页切换
    watch(activeTab, (newTab) => {
      if (newTab === 'favorites' && favorites.attractions.length === 0 && favorites.routes.length === 0) {
        fetchUserFavorites()
      }
    })

    onMounted(async () => {
      await fetchUserProfile()
      await fetchUserPosts()
    })

    return {
      loading,
      postsLoading,
      favoritesLoading,
      user,
      stats,
      posts,
      favorites,
      activeTab,
      favoritesTab,
      isCurrentUser,
      avatarUrl,
      toggleLike,
      showComments,
      viewAttraction,
      viewRoute,
      goBack,
      formatTime,
      getImageUrl
    }
  }
}
</script>

<style scoped>
.user-profile {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
}

.profile-content {
  margin-top: 20px;
}

.user-info-card {
  margin-bottom: 20px;
  border-radius: 16px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(200, 16, 46, 0.08);
  transition: all 0.3s ease;
}

.user-info-card:hover {
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.16);
  transform: translateY(-2px);
  border-color: rgba(212, 175, 55, 0.3);
}

.user-header {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.user-details {
  flex: 1;
}

.user-details h2 {
  margin: 0 0 10px 0;
  color: #303133;
}

.user-email,
.user-phone {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.user-stats {
  display: flex;
  gap: 30px;
  margin-top: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  transition: all 0.3s ease;
}

.stat-item:hover .stat-value {
  transform: scale(1.1);
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.profile-tabs {
  margin-top: 20px;
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.post-card {
  transition: all 0.3s;
  border-radius: 12px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(200, 16, 46, 0.08);
}

.post-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.16);
  border-color: rgba(212, 175, 55, 0.3);
}

.post-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.post-user-info h4 {
  margin: 0;
  font-size: 16px;
}

.post-time {
  font-size: 12px;
  color: #909399;
}

.post-content {
  margin-bottom: 15px;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.post-image {
  width: 150px;
  height: 150px;
  border-radius: 4px;
}

.post-footer {
  display: flex;
  gap: 10px;
}

.favorites-list {
  margin-top: 20px;
}

.favorite-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(200, 16, 46, 0.08);
}

.favorite-card:hover {
  transform: translateY(-4px) scale(1.02);
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.16);
  border-color: rgba(212, 175, 55, 0.3);
}

.favorite-image {
  width: 100%;
  height: 200px;
  border-radius: 4px;
  margin-bottom: 10px;
}

.favorite-price {
  color: #D4AF37;
  font-weight: bold;
  font-size: 18px;
}

.route-favorite-card {
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 12px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(200, 16, 46, 0.08);
}

.route-favorite-card:hover {
  transform: translateY(-4px) scale(1.01);
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.16);
  border-color: rgba(212, 175, 55, 0.3);
}

.route-favorite-card h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

/* 响应式设计：移动端图片栅格 */
@media (max-width: 768px) {
  .post-images {
    gap: 8px;
  }
  .post-image {
    width: calc(50% - 4px);
    height: 140px;
  }
}

@media (max-width: 480px) {
  .post-image {
    width: 100%;
    height: 160px;
  }
}
</style>

